package com.polaris.live.common.mvvm.activity

import android.content.Context
import android.content.res.Resources
import android.os.Bundle
import android.view.View
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.StringUtils
import com.hjq.language.MultiLanguages
import com.polaris.live.common.mvvm.ext.getVmClazz
import com.polaris.live.common.mvvm.ext.notNull
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.util.ImmersionBarBuilder
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.loading.LoadingUtils
import com.polaris.live.common.util.loading.OnCancelListener
import com.polaris.live.common.util.loading.OnDismissListener
import com.polaris.live.translation.R
import me.jessyan.autosize.AutoSizeCompat
import java.util.UUID

/**
 * ViewModelActivity是基类，把ViedModel注入进来了
 *
 * @author Created by 半仙 on 2023/7/31/031 15:13
 */
abstract class BaseVmActivity<VM : BaseViewModel> : AppCompatActivity() {

    private lateinit var _viewModel: VM
    val mViewModel: VM get() = _viewModel

    private var pageId: String? = null

    abstract fun layoutId(): Int

    abstract fun initView(savedInstanceState: Bundle?)

    abstract fun showLoading(
        message: String = StringUtils.getString(R.string.loading),
        cancelable: Boolean = false,
        hasShadowBg: Boolean = false,
        cancelTime: Long = 15 * 1000L,
        waitTime: Long = 500L,
        useView: Boolean = true,
        onCancelListener: OnCancelListener? = null,
        onDismissListener: OnDismissListener? = null,
    )

    abstract fun dismissLoading(waitTime: Long = 0L)

    override fun attachBaseContext(newBase: Context?) {
        // 绑定语种
        super.attachBaseContext(MultiLanguages.attach(newBase))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (savedInstanceState != null) {
            AppUtils.relaunchApp()
        }

        initDataBind().notNull({
            setContentView(it)
        }, {
            setContentView(layoutId())
        })
        init(savedInstanceState)

        initImmersionBar()
    }

    private fun init(savedInstanceState: Bundle?) {
        _viewModel = createViewModel()
        registerUiChange()
        initView(savedInstanceState)
        createObserver()
    }

    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(this)[getVmClazz(this)]
    }

    /**
     * 创建liveData数据观察者
     */
    abstract fun createObserver()

    /**
     * 注册UI 事件
     */
    private fun registerUiChange() {
        //显示弹窗
        mViewModel.loadingChange.showDialog.observeInActivity(this) {
            showLoading(
                it.message,
                it.cancelable,
                it.hasShadowBg,
                it.cancelTime,
                it.waitTime,
                it.useView,
                it.onCancelListener,
                it.onDismissListener
            )
        }
        //关闭弹窗
        mViewModel.loadingChange.dismissDialog.observeInActivity(this) {
            dismissLoading()
        }
    }

    /**
     * 供子类BaseVmDbActivity 初始化viewBinding操作
     */
    abstract fun initDataBind(): View?

    open fun initImmersionBar() {
        NavigationBarUtils.setImmersionBar(this) {
            buildImmersionBar()
        }
    }

    open fun ImmersionBarBuilder.buildImmersionBar() {
    }

    /**
     * 获取页面唯一id
     */
    fun getPageId(): String {
        val pageId = pageId
        if (pageId != null) {
            return pageId
        }

        return UUID.randomUUID().toString().replace("-", "").also {
            this.pageId = it
        }
    }

    override fun getResources(): Resources {
        runOnUiThread {
            AutoSizeCompat.autoConvertDensityOfGlobal(super.getResources())
        }
        return super.getResources()
    }
}

/**
 * 打开等待框
 */
fun BaseVmActivity<*>.showLoading(
    @StringRes message: Int,
    cancelable: Boolean = false,
    hasShadowBg: Boolean = true,
    cancelTime: Long = 15 * 1000L,
    waitTime: Long = 500L,
    useView: Boolean = true,
    onCancelListener: OnCancelListener? = null,
    onDismissListener: OnDismissListener? = null,
) {
    LoadingUtils.showLoadingDialog(
        this,
        getString(message),
        cancelable,
        hasShadowBg,
        cancelTime,
        waitTime,
        useView,
        onCancelListener,
        onDismissListener
    )
}